package org.csu.mypetstore.web.servlet;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.UserCart;
import org.csu.mypetstore.service.UserCartService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "UserCartServlet", value = "/UserCartServlet")
public class UserCartServlet extends HttpServlet {
    private static String USER_CART="/WEB-INF/jsp/cart/ViewCart.jsp";
    private static String MAIN="/WEB-INF/jsp/cart/Cart.jsp";
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         HttpSession session=request.getSession();
         UserCartService service=new UserCartService();
         UserCart usercart=new UserCart();
         List<UserCart> userCartList=new ArrayList<UserCart>();

         usercart.setUserid(((Account)(session.getAttribute("accounts"))).getUsername());
         usercart.setItemid(request.getParameter("itemId"));
//        System.out.println(request.getParameter("itemid"));
//        System.out.println(request.getParameter("quantity"));
        usercart.setNumber(Integer.valueOf(request.getParameter("quantity")) );
        usercart.setDescn(service.getUserCart(usercart.getItemid()).getDescn());
        usercart.setListprice(service.getUserCart(usercart.getItemid()).getListprice());
        usercart.setProductid(service.getUserCart(usercart.getItemid()).getProductid());
        usercart.setTotalprice(usercart.getListprice()*usercart.getNumber());
         //cart.setListprice(Double.parseDouble(request.getParameter("listprice")));
         //cart.setProductid(request.getParameter("productid"));

         if(service.selectCartList(usercart))
         {
             service.insertCartList(usercart);
         }
         else
         {
             service.updateCartList(usercart);
         }
         userCartList=service.getCartListByUserid(usercart.getUserid());
         session.setAttribute("userCartList",userCartList);
         session.setAttribute("usercart",usercart);
         request.getRequestDispatcher(MAIN).forward(request,response);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
